package info.leetcode.answer.Array.TwoDimensionalArray.specific;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaolong
 * @version 1.0
 * @description:  螺旋矩阵
 * @date 2024/2/22 9:19
 */
public class SpiralOrder {
    public static void main(String[] args) {
        int [][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        List<Integer> result = spiralOrder(matrix);
        System.out.println(result);
    }

    private static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int transverseIndex = 0 ;
        int directionIndex = 0 ;
        Boolean circulFlag = false ;
        int transverseFlag = 1 ;
        int directionFlag = 1 ;
        while (result.size() != matrix.length * matrix[0].length){
            try {
                //判断横向还是纵向
                if (circulFlag){
                    //纵向
                    if (matrix[transverseIndex][directionIndex] != 101){
                        result.add(matrix[transverseIndex][directionIndex]);
                        matrix[transverseIndex][directionIndex]= 101 ;
                        transverseIndex += transverseFlag ;
                        continue;
                    }
                    circulFlag = !circulFlag;
                    // 指针回退
                    transverseIndex -= transverseFlag ;
                    //指针转向
                    transverseFlag *= -1 ;
                    // 下一步指针移动
                    directionIndex += directionFlag ;
                }else {
                    //横向
                    if (matrix[transverseIndex][directionIndex] != 101){
                        result.add(matrix[transverseIndex][directionIndex]);
                        matrix[transverseIndex][directionIndex]= 101 ;
                        directionIndex += directionFlag  ;
                        continue;
                    }
                    circulFlag = !circulFlag;
                    directionIndex -= directionFlag  ;
                    directionFlag *= -1 ;
                    transverseIndex += transverseFlag ;
                }
            }catch (IndexOutOfBoundsException e){
                if (circulFlag){
                    // 指针回退
                    transverseIndex -= transverseFlag ;
                    //指针转向
                    transverseFlag *= -1 ;
                    // 下一步指针移动
                    directionIndex += directionFlag ;
                }else {
                    directionIndex -= directionFlag  ;
                    directionFlag *= -1 ;
                    transverseIndex += transverseFlag ;
                }
                circulFlag = !circulFlag;
            }
        }
        return result;
    }
}
